import { defineMessages } from 'react-intl';
import { message } from 'antd';
import { routerRedux, Router, RouteProps } from 'dva/router';
import { Logger, strEnum, settings } from '../utils';
import { login } from '../services/app';

// typescript 定义
import { Dispatch } from 'redux';
import { History } from 'history';
import { User } from './types';
// 登陆用的dva model

// 定义登陆相关的国际化messages
const messages = defineMessages({
  // 登陆成功
  loginSuccess: {
    id: 'Login.loginSuccess',
    defaultMessage: 'Login succesed'
  },
  // 登陆失败
  loginFailure: {
    id: 'Login.loginFailure',
    defaultMessage: 'Login failured'
  },
  authenticating: {
    id: 'Login.authenticating',
    defaultMessage: 'Authenticating...'
  }
});

export const namespace = 'login';

export const Action = strEnum([
  'login',
  'loginSuccess',
  'loginFailure'
]);

export interface State {

}

const state: State = {

}

export default {
  namespace,
  state,
  subscriptions: {
  },
  effects: {
    *[Action.login] ({ payload }: any , { select, call, put }) {
      Logger.info('login');
      // 获取国际化工具
      const { intl } = yield select(state => state);
      // 加载提示信息
      // Verifying authenticating
      settings.showLoadingMsg(intl.formatMessage(messages.authenticating));
      // 调用登陆方法
      const result = yield call(login, payload);
      const { success, data } = result;
      if (success) {
        // 调用app模块的登陆验证方法
        yield put({ type: 'app/auth' });
        yield put({
          type: Action.loginSuccess,
          payload: { intl }
        });
      } else {
        // 有错
        yield put({
          type: Action.loginFailure,
          payload: { intl }
        });
      }
    }
  },
  reducers: {
    [Action.loginSuccess] (state: State, { payload: { intl } }) {
      // 登陆成功
      settings.hideLoadingMsg();
      message.info(intl.formatMessage(messages.loginSuccess));
      return state;
    },
    [Action.loginFailure] (state: State, { payload: { intl } }) {
      // 登陆失败
      settings.hideLoadingMsg();
      message.error(intl.formatMessage(messages.loginFailure));
      return state;
    }
  }
}
